package cn.wangkai.peanut.searchchangefile.tools;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

import cn.wangkai.peanut.searchchangefile.swtdesigner.SWTResourceManager;

public class WKCalendar extends Dialog implements MouseListener {

	private final SimpleDateFormat formattermoth = new SimpleDateFormat("yyyy-MM");
	/**
	 * 默认背景色
	 */
	private final Color COLORWHILE = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE);
	
	private final Color COLORBLUE = Display.getCurrent().getSystemColor(SWT.COLOR_BLUE);
	
	private final Color COLORBLACK = Display.getCurrent().getSystemColor(SWT.COLOR_BLACK);
	

	private final Color HEAD_BGCOLOR = SWTResourceManager.getColor(128, 128, 128);
	private final Color HEAD_COLOR = SWTResourceManager.getColor(192, 192, 192);
	
	private final Color TODAYCOLOR = SWTResourceManager.getColor(178,34,34);
	
	private CLabel nowLabel;
	// 当前的日期
	private Date nowDate = null;
	// 用户选择的日期
	private String selectedDate = null;
	private String thismonth = formattermoth.format(Calendar.getInstance().getTime());
	private Shell shell = null;
	private int bbwidth = 15;
	private int bbheight = 12;
	private Button monthUp = null;
	private Button monthNext = null;
	private CLabel[] days = new CLabel[42];
	

	


	public WKCalendar(Shell parent, int style) {
		super(parent, style);
	}

	public WKCalendar(Shell parent) {
		this(parent, 0);
	}

	/**
	 * 获取某年某月的最后一天
	 * 
	 * @param year 年
	 * @param month 月
	 * @return 最后一天
	 */
	private int getLastDayOfMonth(int year, int month) {
		if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
			return 31;
		} else if (month == 4 || month == 6 || month == 9 || month == 11) {
			return 30;
		} else if (month == 2) {
			if (isLeapYear(year)) {//计算闰月
				return 29;
			} else {
				return 28;
			}
		}
		return 0;
	}

	/**
	 * 是否闰年
	 * 
	 * @param year 年
	 * @return
	 */
	public boolean isLeapYear(int year) {
		return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
	}

	/**
	 * 移动月份
	 * 
	 * @param field the calendar field.
	 * 
	 * @param value
	 */
	private void moveTo(int field, int value) {
		Calendar now = Calendar.getInstance();
		now.setTime(nowDate);
		now.add(field, value);
		nowDate = now.getTime();
		nowLabel.setText(formattermoth.format(nowDate));
		setDayForDisplay(now);
	}

	private void setDayForDisplay(Calendar now) {
		int currentDay = now.get(Calendar.DATE);
		now.add(Calendar.DAY_OF_MONTH, -(now.get(Calendar.DATE) - 1));
		int startIndex = now.get(Calendar.DAY_OF_WEEK) - 1;
		int year = now.get(Calendar.YEAR);
		int month = now.get(Calendar.MONTH) + 1;
		int lastDay = this.getLastDayOfMonth(year, month);
		int endIndex = startIndex + lastDay - 1;
		int startday = 1;
		for (int i = 0; i < 42; i++) {
			Color temp = days[i].getBackground();
			if (temp.equals(COLORBLUE)) {
				days[i].setBackground(COLORWHILE);
			}
		}
		for (int i = 0; i < 42; i++) {
			if (i >= startIndex && i <= endIndex) {
				days[i].setText("" + startday);
				days[i].setForeground(COLORBLACK);
				if(StringUtils.equalsIgnoreCase(thismonth,nowLabel.getText())&&startday == currentDay) days[i].setForeground(TODAYCOLOR);
				startday++;
			} else {
				days[i].setText("");
			}
		}
	}

	/**
	 * 下一个月
	 */
	public void nextMonth() {
		moveTo(Calendar.MONTH, 1);
	}
	
	/**
	 * 上一个月
	 */
	public void previousMonth() {
		moveTo(Calendar.MONTH, -1);
	}

	/**
	 * 鼠标点击
	 */
	public void mouseDoubleClick(MouseEvent e) {
		CLabel day = (CLabel) e.getSource();
		if (!day.getText().equals("")) {
			int sday = NumberUtils.toInt(day.getText(), 1);
			if (sday < 10) {
				this.selectedDate = String.format("%s-0%d", nowLabel.getText(), sday);
			} else {
				this.selectedDate = String.format("%s-%d", nowLabel.getText(), sday);
			}
			this.shell.close();
		}
	}

	public void mouseDown(MouseEvent e) {
	}

	public void mouseUp(MouseEvent e) {
	}

	/**
	 * 返回用户选择的年月日信息
	 * 
	 * @return
	 */
	public Object open(Point point) {
		Shell parent = getParent();
		shell = new Shell(SWT.DIALOG_TRIM | SWT.SYSTEM_MODAL);
		shell.setVisible(false);
		shell.addFocusListener(new FocusAdapter() {
			public void focusLost(FocusEvent arg0) {
				// shell.close();
			}
		});
		shell.setLocation(point);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.verticalSpacing = 0;
		gridLayout.horizontalSpacing = 0;
		gridLayout.marginHeight = 0;
		gridLayout.marginWidth = 5;
		shell.setLayout(gridLayout);
		shell.setText("秋水日历");
		shell.setSize(160, 186);
		
		
		
		
		final Composite composite = new Composite(shell, SWT.NONE);
		final GridData gridData_1 = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
		gridData_1.heightHint = 25;
		gridData_1.widthHint = 150;
		composite.setLayoutData(gridData_1);
		final GridLayout gridLayout_1 = new GridLayout();
		gridLayout_1.numColumns = 3;
		composite.setLayout(gridLayout_1);
		monthUp = new Button(composite, SWT.ARROW | SWT.LEFT | SWT.FLAT);
		monthUp.setText("<<");
		monthUp.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				previousMonth();
			}
		});

		nowLabel = new CLabel(composite, SWT.CENTER);
		final GridData gridData_8 = new GridData();
		gridData_8.widthHint = 100;
		nowLabel.setLayoutData(gridData_8);
		nowLabel.setText(formattermoth.format(new Date()));
		
		monthNext = new Button(composite, SWT.ARROW | SWT.RIGHT | SWT.FLAT);
		monthNext.setLayoutData(new GridData());
		monthNext.setText(">>");
		monthNext.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				nextMonth();
			}
		});
		
		final Composite composite_2 = new Composite(shell, SWT.NONE);
		composite_2.setBackground(COLORWHILE);
		GridLayout gridLayout2 = new GridLayout();
		gridLayout2.verticalSpacing = 0;
		gridLayout2.horizontalSpacing = 0;
		gridLayout2.marginHeight = 0;
		gridLayout2.marginWidth = 0;
		composite_2.setLayout(gridLayout2);
		final Composite composite_1 = new Composite(composite_2, SWT.NONE);
		composite_1.setBackground(HEAD_BGCOLOR);
		composite_1.setLayoutData(new GridData());
		final GridLayout gridLayout_2 = new GridLayout();
		gridLayout_2.numColumns = 7;
		composite_1.setLayout(gridLayout_2);
		String[] day = { "日", "一", "二", "三", "四", "五", "六" };
		for (int i = 0; i < day.length; i++) {
			CLabel daytop = new CLabel(composite_1, SWT.CENTER);
			daytop.setForeground(HEAD_COLOR);
			daytop.setBackground(HEAD_BGCOLOR);
			final GridData daygridData = new GridData();
			daygridData.heightHint = bbheight;
			daygridData.widthHint = bbwidth;
			daytop.setLayoutData(daygridData);
			daytop.setRedraw(true);
			daytop.setText(day[i]);
		}

		final Composite composite_3 = new Composite(composite_2, SWT.NONE);
		composite_3.setBackground(COLORWHILE);
		final GridLayout gridLayout_3 = new GridLayout();
		gridLayout_3.numColumns = 7;
		composite_3.setLayout(gridLayout_3);
		for (int i = 0; i < 42; i++) {
			days[i] = new CLabel(composite_3, SWT.FLAT | SWT.CENTER);
			final GridData daygridData = new GridData();
			daygridData.heightHint = bbheight;
			daygridData.widthHint = bbwidth;
			days[i].setLayoutData(daygridData);
			days[i].setBackground(COLORWHILE);
			days[i].addMouseListener(this);
			days[i].setToolTipText("双击选择");
			days[i].addMouseTrackListener(new MouseTrackListener() {
				@Override
				public void mouseHover(MouseEvent e) {
				}
				
				@Override
				public void mouseExit(MouseEvent e) {
					//移入事件  
					CLabel day = (CLabel) e.getSource();
					if (!StringUtils.isEmpty(day.getText())) {
						day.setBackground(COLORWHILE);
					}
				}
				@Override
				public void mouseEnter(MouseEvent e) {
					//移出事件  
					CLabel day = (CLabel) e.getSource();
					if (!StringUtils.isEmpty(day.getText())) {
						day.setBackground(HEAD_BGCOLOR);
					}					
				}
			});
		}

		Calendar now = Calendar.getInstance();
		nowDate = now.getTime();
		setDayForDisplay(now);
		shell.open();

		Display display2 = parent.getDisplay();
		while (!shell.isDisposed()) {
			if (!display2.readAndDispatch()) {
				display2.sleep();
			}
		}
		return selectedDate;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Display display = new Display();
		final Shell shell = new Shell(display);
		shell.setText("日历");
		FillLayout fl = new FillLayout();
		shell.setLayout(fl);

		Button open = new Button(shell, SWT.PUSH);
		open.setText("日历");
		open.addSelectionListener(new SelectionAdapter() {
			@SuppressWarnings("unused")
			public void widgetSelected(SelectionEvent e) {
				WKCalendar stc = new WKCalendar(shell);
				WKCalendar calendar = new WKCalendar(shell);
				Point point = new Point(shell.getLocation().x + 7, 47 + shell.getLocation().y);
				System.out.println(stc.open(point));
			}
		});
		shell.pack();
		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}
}
